<?php
/**
 * Ws 优化  基础类库
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/3 0003
 * Time: 18:05
 */

class Ws {
    protected $host = '192.168.3.221';
    protected $port = 8812;

    public $ws = null;
    public function __construct()
    {
        $this->ws = new swoole_websocket_server($this->host, $this->port);

        //设置静态文件的访问路径
        $this->ws->set([
            'worker_num' => 2,
            'task_worker_num' => 2,
            'enable_static_handler' => true,
            'document_root' => '/data/wwwroot/www/swoole-demo/mooc/data/',
        ]);

        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('task', [$this, 'onTask']);
        $this->ws->on('finish', [$this, 'onFinish']);
        $this->ws->on('close', [$this, 'onClose']);

        $this->ws->start();
    }

    /**
     * 监听ws连接事件
     * @param $ws
     * @param $request
     */
    public function onOpen($ws, $request)
    {
        var_dump($request->fd);
//        if($request->fd == 1){
            //每2s执行一次定时器
//            swoole_timer_tick(2000, function($timer_id) use($ws, $request){
//                echo "2s-timer_id:{$timer_id}\n";
//                $ws->push($request->fd, "2s-timer_id:".time());
//            });
//        }

    }

    /**
     * 监听ws消息事件
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws, $frame)
    {
        echo "server-push-message:{$frame->data}\n";
        // todo 5s
        $data = [
            'fd' => $frame->fd,
            'task' => 1
        ];
//        $ws->task($data);

        swoole_timer_after(5000, function() use($ws, $frame){
            echo "5s-after\n";
            $ws->push($frame->fd, "server-timer-after:");
        });
        $ws->push($frame->fd, "server-push:" .date('Y-m-d H:i:s'));
    }

    /**
     * 任务
     * @param $serv swoole_server对象
     * @param $task_id  任务id
     * @param $worker_id worker进程id
     * @param $data 任务的内容
     */
    public function onTask($serv, $task_id, $worker_id, $data)
    {
        print_r($data);
        //耗时场景 5s
        sleep(5);
        return $data['fd'];  //告诉worker，调finish
    }

    /**
     * 结束任务
     * @param $serv
     * @param $task_id  任务id
     * @param $data 任务处理的结果内容,ontask方法return的内容
     */
    public function onFinish($serv, $task_id, $data)
    {
        echo "takdId: {$task_id}\n";
        echo "finish-data-success:{$data}\n";
        $serv->push($data, '5s后的数据');
    }

    /**
     * 监听ws关闭事件
     * @param $ws
     * @param $fd
     */
    public function onClose($ws, $fd)
    {
        echo "clientid:{$fd}\n";
    }

}

$obj = new Ws();









